package com.xianye.erp.controller;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.TaobaoUtils;
import com.taobao.api.request.AliexpressLogisticsRedefiningGetonlinelogisticsinfoRequest;
import com.taobao.api.request.AliexpressPostproductRedefiningFindaeproductbyidRequest;
import com.taobao.api.response.AliexpressLogisticsRedefiningGetonlinelogisticsinfoResponse;
import com.taobao.api.response.AliexpressPostproductRedefiningFindaeproductbyidResponse;
import com.xianye.erp.bean.Store;
import com.xianye.erp.bean.User;
import com.xianye.erp.controller.base.BaseController;
import com.xianye.erp.dao.base.DaoSupport;
import com.xianye.erp.factory.ApiFacade;
import com.xianye.erp.service.order.impl.ExpressOrderAPI;
import com.xianye.erp.service.order.impl.OrderService;
import com.xianye.erp.service.order.impl.RefreshOrderException;
import com.xianye.erp.service.order.impl.RefreshOrderService;
import com.xianye.erp.service.order.impl.RefreshOrderStatus;
import com.xianye.erp.service.product.impl.RefreshProductService;
import com.xianye.erp.util.*;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value="/")
public class IndexController extends BaseController{


	@Autowired
	private DaoSupport dao;
	@Autowired
	private ApiFacade apiFacade;
	@Autowired
	private RefreshProductService refreshProductService;
	@Autowired
	private RefreshOrderService refreshOrderService;
	@Autowired
	private RefreshOrderStatus refreshOrderStatus;

    @Autowired
	private RefreshOrderException refreshOrderException;
    @Autowired
    private ExpressOrderAPI expressOrderAPI;
    @Autowired
    private OrderService orderService;
    
	@RequestMapping("/")
	public @ResponseBody String index(HttpSession session) throws ApiException{
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/login");
		TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "24748718", "6b74fcbc159523b94c93c6786347bbf0");
		AliexpressLogisticsRedefiningGetonlinelogisticsinfoRequest req = new AliexpressLogisticsRedefiningGetonlinelogisticsinfoRequest();
		//req.setChinaLogisticsId("LA234234CN");
		//req.setInternationalLogisticsId("LP00038357949881");
		//req.setLogisticsStatus("CLOSED");
		//req.setGmtCreateEndStr("2016-06-27 18:15:00");
		//req.setPageSize(10L);
		//req.setQueryExpressOrder(false);
		//req.setCurrentPage(1L);
		req.setOrderId(90635934536935L);
		AliexpressLogisticsRedefiningGetonlinelogisticsinfoResponse rsp = client.execute(req, "50003500900s1e049a8cQ2s7iGswtyC83gtglq9RTl9Edr3KzXCFjwlafZOHSBLPB5N");
		System.out.println(rsp.getBody());
		return rsp.getBody();
	}

	
	@RequestMapping("/refreshOrder")
	public @ResponseBody String refreshOrder(){
		try {
			PageData pd = new PageData();
			pd = this.getPageData();
			refreshOrderService.refresh(pd.getString("start"),pd.getString("end"),null);
			return returnJSON(true,"success","");
		}catch (Exception e){
			e.printStackTrace();
			return returnJSON(false,"fail","");
		}
	}
	@RequestMapping("/refreshOneStoreOrder")
	public @ResponseBody String refreshOneStoreOrder(){
		try {
			PageData pd = new PageData();
			pd = this.getPageData();
			refreshOrderService.refreshOne(pd.getString("storeId"),pd.getString("start"),pd.getString("end"),null);
			return returnJSON(true,"success","");
		}catch (Exception e){
			e.printStackTrace();
			return returnJSON(false,"fail","");
		}
	}
	@RequestMapping("/getOrderById")
	public @ResponseBody String getOrderById(){
		try {
			PageData pd = new PageData();
			pd = this.getPageData();
			System.out.println(pd.toString());
			PageData store = (PageData) dao.findForObject("StoreMapper.findByStoreId", pd);
			System.out.println(store.toString());
			JSONObject res = expressOrderAPI.getJSONOrderDetail(store, Long.parseLong(pd.getString("orderId")));
			return returnJSON(true,"success",res.toString());
		}catch (Exception e){
			e.printStackTrace();
			return returnJSON(false,"fail","");
		}
	}
	@RequestMapping("/refreshOrderById")
	public @ResponseBody String refreshOrderById(){
		try {
			PageData pd = new PageData();
			pd = this.getPageData();
			List<PageData> list = (List<PageData>) dao.findForList("OrderMapper.findNobuyerinfoOrder", new PageData());
			for(int i=0;i<list.size();i++){
				PageData order = list.get(i);
				PageData s = new PageData();
				s.put("storeId", order.get("STORE_ID"));
				PageData store = (PageData) dao.findForObject("StoreMapper.findByStoreId", s);
				JSONObject res = expressOrderAPI.getJSONOrderDetail(store, Long.parseLong(order.getString("orderId")));
				JSONObject receipt_address = res.getJSONObject("receipt_address");
				JSONObject buyer_info = res.getJSONObject("buyer_info");
				saveBuyer_info(buyer_info, order.getString("orderId"));
				saveReceiptaddress(receipt_address,order.getString("orderId"));
			}					
			return returnJSON(true,"success",null);
		}catch (Exception e){
			e.printStackTrace();
			return returnJSON(false,"fail","");
		}
	}
	public void saveReceiptaddress(JSONObject oo,String orderId) throws Exception{
		PageData pd = new PageData();
		pd.put("orderId", orderId);
		pd.put("address", oo.get("address"));
		pd.put("address2", oo.get("address2"));
		pd.put("city", oo.get("city"));
		pd.put("contactPerson", oo.get("contact_person"));
		pd.put("country", oo.get("country"));
		pd.put("detailAddress", oo.get("detail_address"));
		pd.put("mobileNo", oo.get("mobile_no"));
		pd.put("phoneArea", oo.get("phone_area"));
		pd.put("phoneCountry", oo.get("phone_country"));
		pd.put("phoneNumber", oo.get("phone_number"));
		pd.put("province", oo.get("province"));
		pd.put("zip", oo.get("zip"));
		pd.put("CREATE_DATE", new Date());
		orderService.save_receiptaddress(pd);
	}
	public void saveBuyer_info(JSONObject oo,String orderId) throws Exception{
		PageData pd = new PageData();
		pd.put("orderId", orderId);
		pd.put("country", oo.get("country"));
		pd.put("firstName", oo.get("firstName"));
		pd.put("lastName", oo.get("lastName"));
		pd.put("loginId", oo.get("loginId"));
		pd.put("Email", oo.get("Email"));
		pd.put("CREATE_DATE", new Date());
		orderService.save_buyerinfo(pd);
	}
	@RequestMapping("/test1")
	public @ResponseBody String test1(){
		try {
			refreshOrderException.refresh();
			return returnJSON(true,"success","");
		}catch (Exception e){
			e.printStackTrace();
			return returnJSON(false,"fail","");
		}

	}

	@RequestMapping("/refreshProduct")
	public @ResponseBody String refreshProduct(){
		try {
			PageData pd = new PageData();
			pd = this.getPageData();
			refreshProductService.refreshStoreById(pd);
			return returnJSON(true,"success","");
		}catch (Exception e){
			e.printStackTrace();
			return returnJSON(false,"fail","");
		}

	}
	@RequestMapping("/test4")
	public @ResponseBody String test4() throws  Exception{
		TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "24748718", "6b74fcbc159523b94c93c6786347bbf0");
		AliexpressPostproductRedefiningFindaeproductbyidRequest req = new AliexpressPostproductRedefiningFindaeproductbyidRequest();
		req.setProductId(32848504536L);
		AliexpressPostproductRedefiningFindaeproductbyidResponse rsp = client.execute(req, "50002701b06sfGqdXC12b7e03cetfLUydGgPjwERxmG48uviOqxwtsy4DCcitKew5ps");
		JSONObject res = JSONObject.fromObject(rsp.getBody());
		System.out.println(rsp.getBody());
		System.out.println(new Date().toLocaleString());
		return rsp.getBody();

	}
    
}
